package com.link.play.fit.ai.utils

import android.app.Activity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import com.android.billingclient.api.AcknowledgePurchaseParams
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.ConsumeParams
import com.android.billingclient.api.PendingPurchasesParams
import com.android.billingclient.api.ProductDetails
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.PurchasesUpdatedListener
import com.android.billingclient.api.QueryProductDetailsParams
import com.android.billingclient.api.QueryPurchasesParams
import com.android.billingclient.api.acknowledgePurchase
import com.android.billingclient.api.consumePurchase
import com.android.billingclient.api.queryProductDetails
import com.google.firebase.Firebase
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.analytics
import com.link.play.fit.ai.BuildConfig
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.kv.AuthCache.FIRBASE_SUB_PRODUCT_ID
import com.link.play.fit.ai.kv.AuthCache.SUB_CURRENCY
import com.link.play.fit.ai.kv.AuthCache.SUB_PRICE_VALUE
import com.link.play.fit.ai.kv.AuthCache.isVip
import com.link.play.fit.ai.utils.AppX.applicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import kotlin.math.pow
import kotlin.math.round

object GooglePayUtil {
    const val defaultYearPrice = "US$39.99"
    const val defaultWeekPrice = "US$9.99"
    const val defaultDiscountYearPrice = "US$19.99"
    const val defaultAppPlanPrice = "US$6.99"
    private var mIsSubs = true
    private val TAG = this::class.java.simpleName
    val connectionResult = MutableLiveData(false)

    private val client by lazy {
        BillingClient.newBuilder(applicationContext)
            .setListener(purchasesUpdatedListener)
            .enablePendingPurchases(
                PendingPurchasesParams.newBuilder().enableOneTimeProducts().build()
            )
            // Configure other settings.
            .build()
    }


    private val purchasesUpdatedListener = object : PurchasesUpdatedListener {
        override fun onPurchasesUpdated(
            billingResult: BillingResult,
            purchases: MutableList<Purchase>?,
        ) {
            when (billingResult.responseCode) {
                BillingClient.BillingResponseCode.OK -> {
                    val purchase = purchases?.firstOrNull {
                        it.purchaseState == Purchase.PurchaseState.PURCHASED
                    } ?: return
                    "purchasesUpdatedListener $mIsSubs".d()
                    if (mIsSubs) {
                        MainScope().launch {
                            acknowledgePurchase(purchase)
                        }
                        queryPurchasesAsync()
                    } else {
                        MainScope().launch {
                            consumePurchase(purchase)
                        }
                    }
                    EventUtils.event("google_billing_success", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase.purchaseToken)
                    })

                    "Google bill SUB_CURRENCY $SUB_CURRENCY SUB_PRICE_VALUE $SUB_PRICE_VALUE FIRBASE_SUB_PRODUCT_ID $FIRBASE_SUB_PRODUCT_ID".d()
                    val bundle = Bundle()
                    bundle.putString(FirebaseAnalytics.Param.CURRENCY, SUB_CURRENCY)
                    bundle.putDouble(FirebaseAnalytics.Param.VALUE, SUB_PRICE_VALUE)
                    bundle.putString(FirebaseAnalytics.Param.ITEM_ID, FIRBASE_SUB_PRODUCT_ID)
                    Firebase.analytics.logEvent(FirebaseAnalytics.Event.PURCHASE, bundle)


                    //上报一下单独区分事件回传
                    val bundleOther = Bundle()
                    bundleOther.putString(FirebaseAnalytics.Param.CURRENCY, SUB_CURRENCY)
                    bundleOther.putDouble(FirebaseAnalytics.Param.VALUE, SUB_PRICE_VALUE)
                    bundleOther.putString(FirebaseAnalytics.Param.ITEM_ID, FIRBASE_SUB_PRODUCT_ID)
                    Firebase.analytics.logEvent(
                        if (SUB_PRICE_VALUE > 0) FIRBASE_SUB_PRODUCT_ID else "vip_free",
                        bundleOther
                    )
                }

                else -> {
                    vipResult.postValue(vip)
                }
            }

            val purchase = purchases?.firstOrNull()
            when (billingResult.responseCode) {
                BillingClient.BillingResponseCode.OK -> {}
                BillingClient.BillingResponseCode.BILLING_UNAVAILABLE -> {

                    EventUtils.event("google_billing_error", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase?.purchaseToken)
                        put("info", "处理过程中发生用户计费错误。")
                    })
                }

                BillingClient.BillingResponseCode.DEVELOPER_ERROR -> {
                    EventUtils.event("google_billing_error", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase?.purchaseToken)
                        put("info", "错误使用API导致的错误。")
                    })
                }

                BillingClient.BillingResponseCode.ERROR -> {
                    EventUtils.event("google_billing_error", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase?.purchaseToken)
                        put("info", "API操作期间发生致命错误。")
                    })
                }

                BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED -> {
                    EventUtils.event("google_billing_error", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase?.purchaseToken)
                        put("info", "当前设备上的Play商店不支持请求的功能。")
                    })
                }

                BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED -> {
                    EventUtils.event("google_billing_error", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase?.purchaseToken)
                        put("info", "购买失败，因为该物品已被拥有。")
                    })
                }

                BillingClient.BillingResponseCode.ITEM_NOT_OWNED -> {
                    EventUtils.event("google_billing_error", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase?.purchaseToken)
                        put("info", "对该项目请求的操作失败，因为它不属于用户。")
                    })
                }

                BillingClient.BillingResponseCode.ITEM_UNAVAILABLE -> {
                    EventUtils.event("google_billing_error", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase?.purchaseToken)
                        put("info", "所请求的产品不可购买。")
                    })
                }

                BillingClient.BillingResponseCode.NETWORK_ERROR -> {
                    EventUtils.event("google_billing_error", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase?.purchaseToken)
                        put("info", "操作过程中发生网络错误。")
                    })
                }

                BillingClient.BillingResponseCode.SERVICE_DISCONNECTED -> {
                    EventUtils.event("google_billing_error", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase?.purchaseToken)
                        put("info", "该应用程序未通过Google Play计费库连接到Play商店服务。")
                    })
                }

                BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE -> {
                    EventUtils.event("google_billing_error", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase?.purchaseToken)
                        put("info", "该服务当前不可用。")
                    })
                }

                BillingClient.BillingResponseCode.USER_CANCELED -> {
                    EventUtils.event("google_billing_error", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase?.purchaseToken)
                        put("info", "交易已被用户取消。")
                    })
                }

                else -> {
                    EventUtils.event("google_billing_error", ext = JSONObject().apply {
                        put("productId", google_pay_id)
                        put("purchaseToken", purchase?.purchaseToken)
                        put("info", "未知错误")
                    })
                }
            }
            "onPurchasesUpdated: billingResult:$billingResult".d()
        }
    }

    fun endConnection() {
        client.endConnection()
        connectionResult.postValue(false)
    }

    fun startConnection() {
        if (client.isReady) {
            return
        }
        if (connectionResult.value == true) {
            return
        }

        realStartConnection(3)
    }

    val vipResult = MutableLiveData<Boolean>()

    private fun realStartConnection(retry: Int) {
        client.startConnection(object : BillingClientStateListener {
            override fun onBillingServiceDisconnected() {
                connectionResult.postValue(false)
                if (retry > 0) {
                    realStartConnection(retry - 1)
                }
            }

            override fun onBillingSetupFinished(billingResult: BillingResult) {

                "onBillingSetupFinished: responseCode= ${billingResult.responseCode}".d()
                if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                    connectionResult.postValue(true)
                    //query product state
                    queryPurchasesAsync()
                } else {
                    connectionResult.postValue(false)
                    if (retry > 0) {
                        realStartConnection(retry - 1)
                    }
                }
            }
        })
    }

    suspend fun queryProduct(productId: String, isSubs: Boolean = true): ProductDetails? {
        "queryProduct productId $productId".d()
        val params = getParams(productId, isSubs)
        mIsSubs = isSubs
        val productDetails = withContext(Dispatchers.IO) {
            val productDetailsResult = client.queryProductDetails(params.build())
            return@withContext productDetailsResult.productDetailsList?.firstOrNull {
                //筛选匹配商品

                productId == it.productId
            }
        }

//        productDetails?.subscriptionOfferDetails?.forEach {
//
//            it.pricingPhases.pricingPhaseList.forEach {
//                it.recurrenceMode
//            }
//        }

        "queryProduct: productDetails: ${productDetails?.toString()}".d()
        if (BuildConfig.DEBUG) {
            productDetails?.subscriptionOfferDetails?.forEach {
                for (pricingPhase in it.pricingPhases.pricingPhaseList) {
                    "queryProduct: ----------------- start".d()
                    "Formatted Price:  ${pricingPhase.formattedPrice}".d()
                    "Price Amount Micros: ${pricingPhase.priceAmountMicros}".d()
                    "Price Currency Code: ${pricingPhase.priceCurrencyCode}".d()
                    "Billing Period: ${pricingPhase.billingPeriod}".d()

                    "Recurrence Mode:  ${pricingPhase.recurrenceMode}".d()
                    "Billing Cycle Count: ${pricingPhase.billingCycleCount}".d()

                    "queryProduct:----------------------- end".d()
                }
            }
        }

        return productDetails
    }

    private fun getParams(
        productId: String,
        isSubs: Boolean = true
    ): QueryProductDetailsParams.Builder {
        val params = QueryProductDetailsParams.newBuilder()

        val productList = listOf(
            QueryProductDetailsParams.Product.newBuilder()
                .setProductId(productId)
                .setProductType(if (isSubs) BillingClient.ProductType.SUBS else BillingClient.ProductType.INAPP)
                .build()
        )
        params.setProductList(productList)
        return params
    }


    fun pay(activity: AppCompatActivity, offerToken: String, productDetails: ProductDetails) {
        EventUtils.event("google_billing_click", ext = JSONObject().apply {
            put("productId", google_pay_id)
        })
        val productDetailsParamsList = listOf(
            BillingFlowParams.ProductDetailsParams.newBuilder()
                .setProductDetails(productDetails)
                .setOfferToken(offerToken)
                .build()
        )

        val billingFlowParams = BillingFlowParams.newBuilder()
            .setProductDetailsParamsList(productDetailsParamsList)
            .build()

        val billingResult = client.launchBillingFlow(activity, billingFlowParams)
        if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
            LogX.d(TAG, "pay: success")
        }
    }

    fun launchPurchaseFlow(
        activity: Activity,
        productDetails: ProductDetails,
        payload: String? = null
    ) {
        EventUtils.event("google_billing_click", ext = JSONObject().apply {
            put("productId", google_pay_id)
        })
        val flowParams = BillingFlowParams.newBuilder().apply {
            setProductDetailsParamsList(
                listOf(
                    BillingFlowParams.ProductDetailsParams.newBuilder()
                        .setProductDetails(productDetails)
                        .build()
                )
            )
            payload?.let { setObfuscatedAccountId(it) }
        }.build()

        client.launchBillingFlow(activity, flowParams)
    }

    /**
     * 消费消耗型商品
     * @param purchase
     */
    private suspend fun consumePurchase(purchase: Purchase) {
        val consumeParams =
            ConsumeParams.newBuilder().setPurchaseToken(purchase.purchaseToken).build()
        val consumeResult = withContext(Dispatchers.IO) {
            client.consumePurchase(consumeParams).billingResult
        }

        if (consumeResult.responseCode == BillingClient.BillingResponseCode.OK) {
            "consumePurchase ${consumeResult.responseCode}".d()
            EventBus.getDefault().post("isAppPurchaseVip")
        }
    }

    //确认商品
    private suspend fun acknowledgePurchase(purchase: Purchase) {
        if (purchase.isAcknowledged) {
            return
        }
        val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
            .setPurchaseToken(purchase.purchaseToken)
            .build()
        val ackPurchaseResult = withContext(Dispatchers.IO) {
            client.acknowledgePurchase(acknowledgePurchaseParams)

        }

        if (ackPurchaseResult.responseCode == BillingClient.BillingResponseCode.OK) {
            vip = true
            "======== acknowledgePurchase success ==========".d()
            EventBus.getDefault().post("isVip")
        }
    }

    private var vip = false

    fun isAppVip(): Boolean {
        return vip
    }

    var google_pay_id = ""//订阅上报ID

    /**
     * 查询购买的
     */
    fun queryPurchasesAsync() {
        client.queryPurchasesAsync(
            QueryPurchasesParams.newBuilder()
                .setProductType(BillingClient.ProductType.SUBS)
                .build()
        ) { billingResult, purchases ->

            purchases.forEach {
//                runCatching {
//                    val jsonObject = JSONObject(it.originalJson)
//                    "jsonObject  $jsonObject".d()
//                    product_id = jsonObject.get("productId").toString()
//                    purchase_time = jsonObject.get("purchaseTime").toString()
//                }
                vip = it.isAcknowledged
                "queryPurchasesAsync: responseCod=${billingResult.responseCode} ----it.isAcknowledged:${it.isAcknowledged}-- ${it}  ${it.products.size}".d()

                if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                    MainScope().launch {
                        if (!it.isAcknowledged) {
                            acknowledgePurchase(it)
                            queryPurchasesAsync()
                        }
                    }
                }
            }

            vipResult.postValue(vip)
            isVip = isAppVip()

//            if (BuildConfig.DEBUG) {
//                isVip = true
//            }
            "GooglePay isVip  $isVip   vip:$vip".d()
        }
    }

    fun extractAndCalculateDailyPriceToPlanDays(formattedPrice: String, days: Int): String? {
        try {
            val regex = """[-+]?[0-9]*\.?[0-9]+""".toRegex()
            val matchResult = regex.find(formattedPrice)
            if (matchResult != null) {
                val price = matchResult.value.toDouble()
                // 计算每日价格（除以 365）
                val dailyPrice = roundDouble(price / days, 2)

                // 保留除金额之外的文字
                val textWithoutPrice = formattedPrice.replace(matchResult.value, "")
                return textWithoutPrice + dailyPrice
            } else {
                return null
            }
        } catch (e: Exception) {
            return null
        }
    }

    fun extractAndCalculateDailyPriceToPlanDaysx2(formattedPrice: String, days: Int): String? {
        try {
            val regex = """[-+]?[0-9]*\.?[0-9]+""".toRegex()
            val matchResult = regex.find(formattedPrice)

            if (matchResult != null) {
                // 提取金额并转换为 Double
                val price = matchResult.value.toDouble()
                // 计算每日价格（除以 365）
                val dailyPrice = roundDouble(price * 2 / days, 2)
//            val df = DecimalFormat("#0.00") // 强制保留两位小数
//            val dailyPrice = (price*2 / days)
//            val formatP = df.format(dailyPrice)
                // 保留除金额之外的文字
                val textWithoutPrice = formattedPrice.replace(matchResult.value, "")
                return textWithoutPrice + dailyPrice
            } else {
                return null
            }
        } catch (e: Exception) {
            return null
        }
    }

    fun extractAndCalculateDailyPriceToWeekDay(formattedPrice: String): String? {
        try {
            // 使用正则表达式匹配金额部分
            val regex = """[-+]?[0-9]*\.?[0-9]+""".toRegex()
            val matchResult = regex.find(formattedPrice)

            if (matchResult != null) {
                // 提取金额并转换为 Double
                val price = matchResult.value.toDouble()
                // 计算每日价格（除以 365）
                val dailyPrice = roundDouble(price / 7, 2)

                // 保留除金额之外的文字
                val textWithoutPrice = formattedPrice.replace(matchResult.value, "")
                return textWithoutPrice + dailyPrice
            } else {
                return null
            }
        } catch (e: Exception) {
            return null
        }
    }
    fun extractAndCalculateDailyPriceMonthsToDay(formattedPrice: String): String? {
        try {
            // 使用正则表达式匹配金额部分
            val regex = """[-+]?[0-9]*\.?[0-9]+""".toRegex()
            val matchResult = regex.find(formattedPrice)

            if (matchResult != null) {
                // 提取金额并转换为 Double
                val price = matchResult.value.toDouble()
                // 计算每日价格（除以 365）
                val dailyPrice = roundDouble(price / 30, 2)

                // 保留除金额之外的文字
                val textWithoutPrice = formattedPrice.replace(matchResult.value, "")
                return textWithoutPrice + dailyPrice
            } else {
                return null
            }
        } catch (e: Exception) {
            return null
        }
    }

    fun extractAndCalculateDailyPrice(formattedPrice: String): String? {
        try {
            // 使用正则表达式匹配金额部分
            val regex = """[-+]?[0-9]*\.?[0-9]+""".toRegex()
            val matchResult = regex.find(formattedPrice)

            if (matchResult != null) {
                // 提取金额并转换为 Double
                val price = matchResult.value.toDouble()
                // 计算每日价格（除以 365）
                val dailyPrice = roundDouble(price / 365, 2)

                // 保留除金额之外的文字
                val textWithoutPrice = formattedPrice.replace(matchResult.value, "")
                return textWithoutPrice + dailyPrice
            } else {
                return null
            }
        } catch (e: Exception) {
            return null
        }
    }

    fun extractAndCalculateDailyPriceToMonth(formattedPrice: String): String? {
        try {
            // 使用正则表达式匹配金额部分
            val regex = """[-+]?[0-9]*\.?[0-9]+""".toRegex()
            val matchResult = regex.find(formattedPrice)

            if (matchResult != null) {
                // 提取金额并转换为 Double
                val price = matchResult.value.toDouble()
                // 计算每日价格（除以 365）
                val dailyPrice = roundDouble(price / 12, 2)

                // 保留除金额之外的文字
                val textWithoutPrice = formattedPrice.replace(matchResult.value, "")
                return textWithoutPrice + dailyPrice
            } else {
                return null
            }
        } catch (e: Exception) {
            return null
        }

    }

    fun extractAndCalculateDailyPriceToDay(formattedPrice: String): String? {
        try {
            val regex = """[-+]?[0-9]*\.?[0-9]+""".toRegex()
            val matchResult = regex.find(formattedPrice)
            if (matchResult != null) {
                // 提取金额并转换为 Double
                val price = matchResult.value.toDouble()
                // 计算每日价格（除以 365）
                val dailyPrice = roundDouble(price / 7, 2)

                // 保留除金额之外的文字
                val textWithoutPrice = formattedPrice.replace(matchResult.value, "")
                return textWithoutPrice + dailyPrice
            } else {
                return null
            }
        } catch (e: Exception) {
            return null
        }
    }

    fun extractAndCalculateDailyPriceToWeek(formattedPrice: String): String? {
        try {

            // 使用正则表达式匹配金额部分
            val regex = """[-+]?[0-9]*\.?[0-9]+""".toRegex()
            val matchResult = regex.find(formattedPrice)

            if (matchResult != null) {
                // 提取金额并转换为 Double
                val price = matchResult.value.toDouble()
                // 计算每日价格（除以 365）
                val dailyPrice = roundDouble(price / 52.14, 2)

                // 保留除金额之外的文字
                val textWithoutPrice = formattedPrice.replace(matchResult.value, "")
                return textWithoutPrice + dailyPrice
            } else {
                return null
            }
        } catch (e: Exception) {
            return null
        }
    }

    fun roundDouble(value: Double, places: Int): Double {
        val factor = 10.0.pow(places)
        return round(value * factor) / factor
    }

    /**
     * 解析带美元符号的价格字符串
     * 示例："$9.99" -> 9.99
     */
    fun parsePriceString(priceStr: String): Double {

//        var cleanStr = ""
//        kotlin.runCatching {
//            // 去除所有非数字和小数点的字符
//             cleanStr = priceStr.replace("[^\\d.]".toRegex(), "")
//            require(cleanStr.isNotEmpty()) { "无法解析价格字符串: $priceStr" }
//            return cleanStr.toDouble()
//        }
//      return 0.0
        try {
            // 去除所有非数字和小数点的字符
            val cleanStr = priceStr.replace("[^\\d.]".toRegex(), "")
            require(cleanStr.isNotEmpty()) { "无法解析价格字符串: $priceStr" }
            return cleanStr.toDouble()
        } catch (e: Exception) {
            return 0.0
        }
    }

    /**
     * 计算节省百分比（支持带美元符号的字符串）
     * @param annualPriceStr 年度价格字符串（如 "$39.99"）
     * @param monthlyPriceStr 月度价格字符串（如 "$9.99"）
     * @param months 分期月数（如 12）
     * @return 节省百分比（如 66.67），失败时返回 null
     */
    fun calculateSavingsPercentageFromStrings(
        annualPriceStr: String,
        monthlyPriceStr: String,
        months: Int
    ): Double? {
        return try {
            // 解析价格
            val annualPrice = parsePriceString(annualPriceStr)
            val monthlyPrice = parsePriceString(monthlyPriceStr)

            // 计算分期总费用
            val totalInstallment = monthlyPrice * months
            require(totalInstallment > 0) { "分期总费用必须大于 0" }

            // 计算节省比例
            ((totalInstallment - annualPrice) / totalInstallment * 100)
                .roundTo2Decimal()
        } catch (e: Exception) {
            e.printStackTrace()
            null // 返回 null 表示计算失败
        }
    }

    // 保留两位小数扩展函数
    fun Double.roundTo2Decimal(): Double {
        return "%.2f".format(this).toDouble()
    }


}


